<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi;

/**
 * 后台用户控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class UserController extends AdminController {

    /**
     * 用户管理首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index(){
        $nickname       =   I('nickname');
        $map['status']  =   array('egt',0);
        $mapa['uid'] = intval(is_login());
        $group = M('AuthGroupAccess')->where($mapa)->find();
        if(intval(is_login()) == 1 || $group['group_id'] == 4){
            $kaka = 0;
            if(is_numeric($nickname)){
                $map['uid|nickname']=   array(intval($nickname),array('like','%'.$nickname.'%'),'_multi'=>true);
            }else{
                $map['nickname']    =   array('like', '%'.(string)$nickname.'%');
            }
        } else {
            $kaka = 1;
            $map['uid'] = is_login();
        }
        $list   = $this->lists('Member', $map);
        int_to_string($list);
        $this->assign('kaka', $kaka);
        $this->assign('_list', $list);
        $this->meta_title = '用户信息';
        $this->display();
    }

    public function selectIndex(){
        // $nickname       =   I('nickname');
        $map['status']  =   array('egt',0);
        $mapa['uid'] = intval(is_login());
        $group = M('AuthGroupAccess')->where($mapa)->find();
        if(intval(is_login()) == 1 || $group['group_id'] == 4){
            if(is_numeric($nickname)){
                $map['uid|nickname']=   array(intval($nickname),array('like','%'.$nickname.'%'),'_multi'=>true);
            }else{
                $map['nickname']    =   array('like', '%'.(string)$nickname.'%');
            }
        } else {
            $map['uid'] = is_login();
        }
        $list   = $this->lists('Member', $map);
        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '用户信息';
        $this->display();
    }

    /**
     * 修改昵称初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updateNickname(){
        $nickname = M('Member')->getFieldByUid(UID, 'nickname');
        $this->assign('nickname', $nickname);
        $this->meta_title = '修改昵称';
        $this->display('updatenickname');
    }

    /**
     * 修改昵称提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitNickname(){
        //获取参数
        $nickname = I('post.nickname');
        $password = I('post.password');
        empty($nickname) && $this->error('请输入昵称');
        empty($password) && $this->error('请输入密码');

        //密码验证
        $User   =   new UserApi();
        $uid    =   $User->login(UID, $password, 4);
        ($uid == -2) && $this->error('密码不正确');

        $Member =   D('Member');
        $data   =   $Member->create(array('nickname'=>$nickname));
        if(!$data){
            $this->error($Member->getError());
        }

        $res = $Member->where(array('uid'=>$uid))->save($data);

        if($res){
            $user               =   session('user_auth');
            $user['username']   =   $data['nickname'];
            session('user_auth', $user);
            session('user_auth_sign', data_auth_sign($user));
            $this->success('修改昵称成功！');
        }else{
            $this->error('修改昵称失败！');
        }
    }

    /**
     * 修改密码初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updatePassword(){
        $this->meta_title = '修改密码';
        $this->display('updatepassword');
    }

    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitPassword(){
        //获取参数
        $password   =   I('post.old');
        empty($password) && $this->error('请输入原密码');
        $data['password'] = I('post.password');
        empty($data['password']) && $this->error('请输入新密码');
        $repassword = I('post.repassword');
        empty($repassword) && $this->error('请输入确认密码');

        if($data['password'] !== $repassword){
            $this->error('您输入的新密码与确认密码不一致');
        }

        $Api    =   new UserApi();
        $res    =   $Api->updateInfo(UID, $password, $data);
        if($res['status']){
            $this->success('修改密码成功！');
        }else{
            $this->error($res['info']);
        }
    }

    /**
     * 用户行为列表
     * @author huajie <banhuajie@163.com>
     */
    public function action(){
        //获取列表数据
        $Action =   M('Action')->where(array('status'=>array('gt',-1)));
        $list   =   $this->lists($Action);
        int_to_string($list);
        // 记录当前列表页的cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);

        $this->assign('_list', $list);
        $this->meta_title = '用户行为';
        $this->display();
    }

    /**
     * 新增行为
     * @author huajie <banhuajie@163.com>
     */
    public function addAction(){
        $this->meta_title = '新增行为';
        $this->assign('data',null);
        $this->display('editaction');
    }

    /**
     * 编辑行为
     * @author huajie <banhuajie@163.com>
     */
    public function editAction(){
        $id = I('get.id');
        empty($id) && $this->error('参数不能为空！');
        $data = M('Action')->field(true)->find($id);

        $this->assign('data',$data);
        $this->meta_title = '编辑行为';
        $this->display('editaction');
    }

    /**
     * 更新行为
     * @author huajie <banhuajie@163.com>
     */
    public function saveAction(){
        $res = D('Action')->update();
        if(!$res){
            $this->error(D('Action')->getError());
        }else{
            $this->success($res['id']?'更新成功！':'新增成功！', Cookie('__forward__'));
        }
    }

    /**
     * 会员状态修改
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function changeStatus($method=null){
        $id = array_unique((array)I('id',0));
        if( in_array(C('USER_ADMINISTRATOR'), $id)){
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] =   array('in',$id);
        switch ( strtolower($method) ){
            case 'forbiduser':
                $this->forbid('Member', $map );
                break;
            case 'resumeuser':
                $this->resume('Member', $map );
                break;
            case 'deleteuser':
                $this->delete('Member', $map );
                break;
            default:
                $this->error('参数非法');
        }
    }

    public function add($realname = '', $username = '', $password = '', $repassword = '', $email = '',$level = '', $address = '', $point = '', $recipient = '', $rephone = ''){
        if(IS_POST){
            /* 检测密码 */
            if($password != $repassword){
                $this->error('密码和重复密码不一致！');
            }

            /* 调用注册接口注册用户 */
            $User   =   new UserApi;
            $uid    =   $User->register($username, $password, $email, $level);
            if(0 < $uid){ //注册成功
                $user = array('realname' => $realname, 'uid' => $uid, 'nickname' => $username, 'level' => $level, 'address' => $address, 'status' => 1, 'point' => $point, 'recipient' => $recipient, 'rephone' => $rephone);
                if(!M('Member')->add($user)){
                    $this->error('用户添加失败！');
                } else {
                    $this->success('用户添加成功！',U('index'));
                }
            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        } else {
            $fields = get_model_attribute(4);
            $this->assign('fields',$fields['1']);
            $this->meta_title = '新增用户';
            $this->display();
        }
    }

    public function changePoint($uid = '',$point = '', $repoint = '', $description = '', $Fruit = ''){
        if(IS_POST){
            $map['uid']=$uid;
            $user['description'] = $description;
            var_dump($point);
            var_dump($repoint);
            if($Fruit == 1){
                $user['point'] = array('exp','point'."+".$repoint);
            } else {
                $user['point'] = array('exp','point'."-".$repoint);
            }
            var_dump($user['point']);die;
            if($repoint < 0){
                $user['total_money'] = array('exp','total_money'.$repoint);
            }
            if(!M('Member')->where($map)->save($user)){
                $this->error('用户更新失败！');
            } else {
                $this->addList($uid, $repoint, $description);
                $this->success('用户更新成功！',U('index'));
            }
        } else {
            $map['uid'] = $uid;
            $data = M('Member')->where($map)->find();
            $fields = get_model_attribute(4);
            $this->assign('fields',$fields['1']);
            $this->meta_title = '积分充值';
            $this->assign('data', $data);
            $this->display();
        }
    }

    /**
     * 会员信息修改
     */
    public function edit($username = '', $password = '', $repassword = '', $level = '',$uid = '', $address = ''){
        if(IS_POST){
            /* 检测密码 */
            if($password != $repassword){
                $this->error('密码和重复密码不一致！');
            }
            $User   =   new UserApi;

            $userm = array('uid' => $uid, 'nickname' => $username, 'level' => $level, 'status' => 1, 'address' => $address);
            if($password){
                $useru['password'] = $this->think_ucenter_md5($password, UC_AUTH_KEY);
            }
            $mapu['id'] = $uid;
            $mapm['uid'] =$uid;
            if(!M('UcenterMember')->where($mapu)->save($useru)&&!M('Member')->where($mapm)->save($userm)){
                $this->error('用户更新失败！');
            } else {
                $this->success('用户更新成功！',U('index'));
            }
        } else {
            $fields = get_model_attribute(4);
            $this->assign('fields',$fields['1']);
            $this->meta_title = '新增用户';
            $this->display();
        }
    }

    /**
     * 會員信息欲修改
     */
    public function reEdit($uid = '') {
        $map['uid'] = $uid;
        $data = M('Member')->where($map)->find();
        $fields = get_model_attribute(4);
        $this->assign('fields',$fields['1']);
        $this->assign('data', $data);
        $this->meta_title = '编辑用户';
        $mapa['uid'] = intval(is_login());
        $group = M('AuthGroupAccess')->where($mapa)->find();
        if(intval(is_login()) == 1 || $group['group_id'] == 4){
            $this->display('edit');
        } else {
            $this->display('edit1');
        }
    }

    /**
     * 加密
     */
    function think_ucenter_md5($str, $key = 'ThinkUCenter'){
        return '' === $str ? '' : md5(sha1($str) . $key);
    }

    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }

/*    public function errorMessage($code = 0) {
        switch ($code) {
            case 1:$error = '已审核';break;
            case 3:$error = '已开方';break;
            case 4:$error = '已划价';break;
            case 5:$error = '已备料';break;
            case 1:$error = '已审核';break;
            case 1:$error = '已审核';break;
            
            default:
                # code...
                break;
        }
    }*/
    public function paidList($uid = ''){
        $map['status']  =   array('egt',0);
        // $map['uid'] = is_login();
        $map['uid'] = $uid;
        $list   = $this->lists('List', $map);
        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '充值记录';
        $this->display();
    }
    public function addList($uid = '', $repoint = '', $description = ''){
        $create_time = date("Y-m-d H:i:s");
        $admin_id = is_login();
        $data = array('uid' => $uid, 'money' => $repoint, 'create_time' => $create_time, 'description' => $description, 'admin_id' => $admin_id);
        if(!M('List')->add($data)){
            $this->error('充值失败!');
        } else {
            // $this->success('充值成功!');
        }
    }

    public function exportdata(){
        $map['id'] = array('in',I('id'));
        $m = M('Member');
        $u = M('UcenterMember');
        $data = M('Member')->join('onethink_ucenter_member ON onethink_member.uid = onethink_ucenter_member.id')->field('onethink_member.uid,onethink_member.nickname,onethink_member.point,onethink_member.level,onethink_ucenter_member.email,onethink_member.address')->where($map)->select();
        // foreach ($data as $key => $value) {
        //  $data[$key]['create_time'] = $value['create_time'] = data
        // }
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");
        $filename="export_excel";
        $headArr=array("用户ID","用户名","积分","会员级别","邮箱","地址");
        $this->getExcel($filename,$headArr,$data);
    }

    private function getExcel($fileName,$headArr,$data){

        //对数据进行检验
        if(empty($data) || !is_array($data)){
            die("data must be a array");
        }
        //检查文件名
        if(empty($fileName)){
            exit;
        }
        $date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";
        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //设置表头
        $key = ord("A");
        foreach($headArr as $v){
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum.'1', $v);
            $key += 1;
        }
        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach($data as $key => $rows){ //行写入
            $span = ord("A");
            foreach($rows as $keyName=>$value){// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j.$column, strip_tags(str_replace('&nbsp;','',$value)));
                $span++;
            }
            $column++;
        }
        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();
        ob_start();
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }

}